package com.hanxiaozhang.io.sockethttp;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈Bio服务端〉
 *
 * @author hanxinghua
 * @create 2023/6/20
 * @since 1.0.0
 */
public class HttpBioServer {


    public static void main(String[] args) throws Exception {

        ServerSocket server = new ServerSocket(9090, 20);

        while (true) {
            // 阻塞1
            Socket client = server.accept();
//            System.out.println(client.getInetAddress());
//            System.out.println(client.getLocalPort());
            System.out.println("client connect success,client port is " + client.getPort());

            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        http(client);
                        client.close();
                        System.out.println("client close");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * Http协议
     *
     * @param client
     * @throws IOException
     */
    private static void http(Socket client) throws IOException {
        // 读取输入流中数据
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        try {
            InputStream in = client.getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            // 每次读取 1024 字节，知道读取完成
            while ((len = in.read(buf)) != 0) {
                byteArrayOut.write(buf, 0, len);
                if (in.available() == 0) {
                    break;
                }
            }
            byte[] bytes = byteArrayOut.toByteArray();
            RequestEntity request = new RequestEntity();
            request.byteToRequest(bytes);
            byte[] responseBytes = handler(request);
            OutputStream ops = client.getOutputStream();
            ops.write(responseBytes);
            ops.flush();
        } finally {
            byteArrayOut.close();
        }
    }

    private static byte[] handler(RequestEntity request) {

        System.out.println("request is " + request);
        Map<String, String> headers = new HashMap<>(4);
        headers.put("Content-Type", "text/plain");
        String body = "success";

        // 假装处理一些逻辑

        ResponseEntity response = new ResponseEntity(200, "OK", headers, body);
        byte[] responseBytes = response.responseToBytes(request);
        System.out.println("response is " + response);

        return responseBytes;
    }


}
